package cz.proks.schoolpupilbook.gae.restlet.resource;

import cz.proks.schoolpupilbook.gae.dao.UserDAO;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.User.Role;
import cz.proks.schoolpupilbook.shared.restlet.LoginDTO;
import cz.proks.schoolpupilbook.shared.restlet.RestMapping;
import cz.proks.schoolpupilbook.shared.util.Tester;

public class UserServerResource extends BaseServerResource implements UserResource {		
	private UserDAO dao = new UserDAO();
	private final String defaultUsername = "admin";
	private final String defaultPassword = "admin";


	@Override
	public User retrieve() {		
		String userId = (String) getRequestAttributes().get(RestMapping.PARAMETER_USER_ID);
		
		
		if (Tester.isEmpty(userId))
			return null;
		
		User user = dao.find(userId);
		return user;				
	}

	@Override
	public void store(User obj) {		
		dao.save(obj);
	}
	
	@Override
	public User login(LoginDTO login) {			
		String username = login.getUsername();
		String password = login.getPassword();
		
		User user = null;
		if (isDefaultLogin(username, password) && !dao.usernameExist(username)) {
			user = getDefaultTeacher();
			dao.save(user);
		}
		
		user = dao.login(username, password);		
		return user;
	}
	
	private boolean isDefaultLogin(String username, String password) {
		return defaultUsername.equals(username) && defaultPassword.equals(password);
	}
	
	private User getDefaultTeacher() {
		User user = new User();
		
		user.setName("Default");
		user.setSurname("User");
		
		user.setUsername(defaultUsername);
		user.setPassword(defaultPassword);
		
		user.setRole(Role.LECTOR);
		
		return user;
	}

}
